package cn.ylyhappy.ideavimbuilder4.recyclerlist;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

import cn.ylyhappy.ideavimbuilder4.R;
import cn.ylyhappy.ideavimbuilder4.model.IdeaVimConfig;
import cn.ylyhappy.ideavimbuilder4.model.OnConfigItemClickListener;

public class MainActivityRecyclerListAdapter extends RecyclerView.Adapter<MainActivityRecyclerListHolder> {

    private ArrayList<IdeaVimConfig> list;
    private final Context context;
    private final OnConfigItemClickListener onConfigItemClickListener;
    private int curPos = -1;

    public MainActivityRecyclerListAdapter(ArrayList<IdeaVimConfig> list, Context context, OnConfigItemClickListener onConfigItemClickListener) {
        this.list = list;
        this.context = context;
        this.onConfigItemClickListener = onConfigItemClickListener;
    }

    @NonNull
    @Override
    public MainActivityRecyclerListHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(this.context).inflate(R.layout.activity_main_expand, parent, false);
        MainActivityRecyclerListHolder holder = new MainActivityRecyclerListHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MainActivityRecyclerListHolder holder, int position) {
        holder.getTv1().setText(list.get(position).getName());
        if (curPos != -1 && curPos != position) {
            setCheckboxPosSelected(position, false);
        }
        holder.getCb1().setChecked(list.get(position).getSelected());
        holder.getCb1().setOnClickListener(e -> {
            this.setCheckboxPosSelected(position, true);
            curPos = holder.getAdapterPosition();
            this.onConfigItemClickListener.onConfigItemClick(this.list.get(position));
            notifyDataSetChanged();
        });
    }

    private void setCheckboxPosSelected(int pos, boolean v) {
        this.list.get(pos).setSelected(v);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public ArrayList<IdeaVimConfig> getList() {
        return list;
    }

    public MainActivityRecyclerListAdapter setList(ArrayList<IdeaVimConfig> list) {
        this.list = list;
        return this;
    }
}
